module add3(input [3:0] in, output reg [3:0] out);

  always @ (in) begin
    case (in)
      4'b0000: out <= 4'b0000;
      4'b0001: out <= 4'b0001;
      4'b0010: out <= 4'b0010;
      4'b0011: out <= 4'b0011;
      4'b0100: out <= 4'b0100;
      4'b0101: out <= 4'b1000;
      4'b0110: out <= 4'b1001;
      4'b0111: out <= 4'b1010;
      4'b1000: out <= 4'b1011;
      4'b1001: out <= 4'b1100;
      default: out <= 4'b0000;
    endcase
  end
endmodule


module bcd8 (input [7:0] binary, output reg [3:0] ones, tens);


  reg [3:0] hundreds;
  wire [3:0] i1,i2,i3,i4,i5,i6,i7;
  wire [3:0] o1,o2,o3,o4,o5,o6,o7;

  assign i1 = {1'b0,binary[7:5]};
  assign i2 = {o1[2:0],binary[4]};
  assign i3 = {o2[2:0],binary[3]};
  assign i4 = {o3[2:0],binary[2]};
  assign i5 = {o4[2:0],binary[1]};
  assign i6 = {1'b0,o1[3],o2[3],o3[3]};
  assign i7 = {o6[2:0],o4[3]};


  add3 a1(i1,o1);
  add3 a2(i2,o2);
  add3 a3(i3,o3);
  add3 a4(i4,o4);
  add3 a5(i5,o5);
  add3 a6(i6,o6);
  add3 a7(i7,o7);


  assign ones = {o5[2:0],binary[0]};
  assign tens = {o7[2:0],o5[3]};
  assign hundreds = {1'b0,o7[3]};

endmodule

module bcd12 (input [11:0] binary, output reg [3:0] ones, tens, hundreds, thousands);

  wire [3:0] i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15,i16,i17,i18;
  wire [3:0] o1,o2,o3,o4,o5,o6,o7,o8,o9,o10,o11,o12,o13,o14,o15,o16,o17,o18;

  assign i1 = {1'b0,binary[11:9]};
  assign i2 = {o1[2:0],binary[8]};
  assign i3 = {o2[2:0],binary[7]};
  assign i4 = {o3[2:0],binary[6]};
  assign i5 = {o4[2:0],binary[5]};
  assign i6 = {o5[2:0],binary[4]};
  assign i7 = {o6[2:0],binary[3]};
  assign i8 = {o7[2:0],binary[2]};
  assign i9 = {o8[2:0],binary[1]};
  assign i10 = {1'b0,o1[3],o2[3],o3[3]};
  assign i11 = {o10[2:0],o4[3]};
  assign i12 = {o11[2:0],o5[3]};
  assign i13 = {o12[2:0],o6[3]};
  assign i14 = {o13[2:0],o7[3]};
  assign i15 = {o14[2:0],o8[3]};
  assign i16 = {1'b0,o10[3],o11[3],o12[3]};
  assign i17 = {o16[2:0],o13[3]};
  assign i18 = {o17[2:0],o14[3]};


  add3 a1(i1,o1);
  add3 a2(i2,o2);
  add3 a3(i3,o3);
  add3 a4(i4,o4);
  add3 a5(i5,o5);
  add3 a6(i6,o6);
  add3 a7(i7,o7);
  add3 a8(i8,o8);
  add3 a9(i9,o9);
  add3 a10(i10,o10);
  add3 a11(i11,o11);
  add3 a12(i12,o12);
  add3 a13(i13,o13);
  add3 a14(i14,o14);
  add3 a15(i15,o15);
  add3 a16(i16,o16);
  add3 a17(i17,o17);
  add3 a18(i18,o18);

  assign ones = {o9[2:0],binary[0]};
  assign tens = {o15[2:0],o9[3]};
  assign hundreds = {o18[2:0],o15[3]};
  assign thousands = {1'b0,o16[3],o17[3],o18[3]};

endmodule



